package com.flyxiaozhu.erp.admin.authorize;

import com.flyxiaozhu.erp.core.entities.AdminUser;
import com.flyxiaozhu.erp.core.utils.CollectionUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class AuthorizeHelper {
    public static AdminUserDetails getUserDetails() {
        return (AdminUserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
    }

    public static AdminUser getUser() {
        return getUserDetails().getAdminUser();
    }

    public static Collection<String> getPermissions() {
        return getPermissions(null);
    }

    public static Collection<String> getPermissions(UserDetails userDetails) {
        if (userDetails == null) {
            userDetails = getUserDetails();
        }
        List<String> permission = CollectionUtils.map(userDetails.getAuthorities(), o -> o.getAuthority().replaceAll("^ROLE_", ""));
        Collections.sort(permission);
        return permission;
    }
}
